package com.tfswue.jqr.service;

import com.tfswue.jqr.entity.Book;
import com.tfswue.jqr.mapper.BookMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class BookService {

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private RedisTemplate<String, Book> redisTemplate;

    public Book getBookById(Long id) {
        String key = "book:" + id;
        Book book = redisTemplate.opsForValue().get(key);
        if (book == null) {
            book = bookMapper.selectById(id);
            if (book != null) {
                redisTemplate.opsForValue().set(key, book, 1, TimeUnit.HOURS);
            }
        }
        return book;
    }

    public void addBook(Book book) {
        bookMapper.insert(book);
        redisTemplate.keys("book:*").forEach(key -> redisTemplate.delete(key));
    }
}
